package com.zzyl.framework.interceptor.impl;

import cn.hutool.core.util.StrUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.MemberThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author: ZHD
 * @Date: 2025/08/20 15:42
 * @Description:
 */
@Component
@Slf4j
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        //获取token
        String token = request.getHeader("authorization");
        if(StrUtil.isBlank(token)){
            //提示用户没有权限
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        try {
            Claims claims = tokenService.parseToken(token);
            if(Objects.isNull(claims)){
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }
            Object memberId = claims.get("memberId");
            if (Objects.isNull(memberId)){
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }
            log.info("用户id:{}", memberId);
            MemberThreadLocal.setMemberId(Long.valueOf(memberId.toString()));

        } catch (Exception e) {
            log.error("token解析失败:{}", e.getMessage());
            throw new BaseException("token解析失败:{}", e.getMessage());
        }
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        MemberThreadLocal.remove();
    }

}
